<template>
  <div class="admin-courses-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1>课程管理</h1>
        <div class="breadcrumb">
          <span>首页</span> / <span>内容管理</span> / <span class="current">课程管理</span>
        </div>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showAddCourseDialog">
          <el-icon><Plus /></el-icon>
          添加课程
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-filter-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="课程标题">
          <el-input v-model="searchForm.title" placeholder="请输入课程标题" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 三面板管理区域 -->
    <div class="three-panel-management">
      <!-- 左侧面板：课程列表 -->
      <div class="left-panel">
        <div class="panel-header">
          <h3>课程列表</h3>
        </div>
        <div class="course-list-container">
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="5" animated />
          </div>
          <div v-else class="course-list">
            <div
                v-for="course in courseList"
                :key="course.id"
                class="course-item"
                :class="{ active: currentCourse?.id === course.id }"
                @click="selectCourse(course)"
            >
              <div class="course-info">
                <div class="course-name">{{ course.name }}</div>
              </div>
              <div class="course-actions">
                <el-button
                    type="danger"
                    size="small"
                    @click.stop="handleDeleteCourse(course)"
                    circle
                    title="删除"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
              v-model:current-page="pagination.pageNum"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="sizes, prev, pager, next"
              :total="pagination.total"
              @size-change="(size) => { pagination.pageSize = size; loadPageCount(); loadCourseList() }"
              @current-change="handlePageChange"
          />
        </div>
      </div>

      <!-- 右侧面板 -->
      <div class="right-panel">
        <!-- 课程详细信息 -->
        <div class="course-detail-panel">
          <div class="panel-header">
            <h3>课程详情</h3>
          </div>
          <div v-if="!currentCourse" class="empty-state">
            <div class="empty-content">
              <el-empty description="请选择一个课程查看详情" />
            </div>
          </div>
          <div v-else class="course-detail-content">
            <div class="detail-layout">
              <div class="cover-section">
                <img :src="currentCourse.coverUrl" alt="课程封面" class="course-cover" />
              </div>
              <div class="description-section">
                <div class="description-content">
                  {{ currentCourse.desc || '暂无描述' }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 内容管理区 -->
        <div class="content-panel">
          <div class="panel-header">
            <h3>内容管理</h3>
          </div>
          <div class="content-wrapper">
            <chapter-view :course_id="currentCourse?.id"></chapter-view>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加课程对话框 -->
    <el-dialog
        v-model="addDialogVisible"
        title="添加课程"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form :model="courseForm" label-width="80px">
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="courseForm.courseName" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="课程描述" prop="courseDesc">
          <el-input
              v-model="courseForm.courseDesc"
              type="textarea"
              rows="4"
              placeholder="请输入课程描述"
          />
        </el-form-item>
        <el-form-item label="课程封面" prop="file">
          <el-upload
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-error="handleUploadError"
              :limit="1"
              :show-file-list="true"
              list-type="picture-card"
              accept="image/*">
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              上传封面
            </el-button>
            <template #tip>
              <div class="el-upload__tip">请上传图片格式文件，大小不超过2MB</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddCourse">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Search, Refresh, Upload } from '@element-plus/icons-vue'
import * as courseApi from '@/api/course'
import { loadImage } from '@/api/file'
import ChapterView from '@/views/admin/courses/cpn/ChapterView.vue'

const courseList = ref([])
const currentCourse = ref(null)
const searchForm = ref({ title: '' })
const loading = ref(false)
const addDialogVisible = ref(false)
const courseForm = ref({ courseName: '', courseDesc: '', file: null })
const pagination = ref({ pageNum: 1, pageSize: 10, total: 0 })

onMounted(() => {
  loadCourseList()
  loadPageCount()
})

const loadCourseList = async () => {
  loading.value = true
  try {
    const response = await courseApi.getCourse(pagination.value.pageNum - 1, pagination.value.pageSize, searchForm.value.title)
    courseList.value = response.data
  } catch (error) {
    ElMessage.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

const loadPageCount = async () => {
  try {
    const response = await courseApi.getPage(pagination.value.pageSize)
    pagination.value.total = response.data
  } catch (error) {
    console.error('获取总页数失败:', error)
  }
}

const selectCourse = async (course) => {
  currentCourse.value = course
  try {
    const response = await courseApi.getCourseDetail(course.id)
    currentCourse.value = response.data
    currentCourse.value.coverUrl = await loadImage(response.data.coverUrl)
  } catch (error) {
    ElMessage.error('获取课程详情失败')
  }
}

const showAddCourseDialog = () => {
  courseForm.value = { courseName: '', courseDesc: '', file: null }
  addDialogVisible.value = true
}

watch(addDialogVisible, (newValue) => {
  if (newValue) {
    courseForm.value = { courseName: '', courseDesc: '', file: null }
  }
})

const handleAddCourse = async () => {
  if (!courseForm.value.courseName) {
    ElMessage.warning('请输入课程名称')
    return
  }
  if (!courseForm.value.file) {
    ElMessage.warning('请上传课程封面')
    return
  }
  try {
    await courseApi.addCourse(courseForm.value)
    ElMessage.success('添加成功')
    addDialogVisible.value = false
    loadCourseList()
    loadPageCount()
  } catch (error) {
    ElMessage.error('添加课程失败')
  }
}

const handleDeleteCourse = async (course) => {
  try {
    await ElMessageBox.confirm(`确定要删除课程「${course.name}」吗？`, '确认删除', { type: 'warning' })
    await courseApi.deleteCourse(course.id)
    ElMessage.success('删除成功')
    loadCourseList()
    loadPageCount()
    if (currentCourse.value?.id === course.id) {
      currentCourse.value = null
    }
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('删除失败')
  }
}

const handleSearch = () => {
  pagination.value.pageNum = 1
  loadCourseList()
  loadPageCount()
}

const handleReset = () => {
  searchForm.value.title = ''
  handleSearch()
}

const handleRefresh = () => {
  handleReset()
}

const handlePageChange = (newPage) => {
  pagination.value.pageNum = newPage
  loadCourseList()
}

const handleUploadError = () => {
  ElMessage.error('封面上传失败')
}

const handleFileChange = (uploadFile) => {
  if (uploadFile?.raw) {
    courseForm.value.file = uploadFile.raw
  }
}
</script>

<style scoped lang="scss">
.admin-courses-container {
  padding: 16px;
  height: 95vh;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  overflow: hidden;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;

  .header-content h1 {
    margin: 0;
    font-size: 20px;
    color: #303133;
  }
  .breadcrumb {
    margin-top: 6px;
    font-size: 13px;
    color: #606266;
    .current { color: #409eff; }
  }
  .header-actions { gap: 8px; }
}

.search-filter-card {
  background: #fff;
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 1px 8px rgba(0,0,0,0.08);
}

.three-panel-management {
  flex: 1;
  display: flex;
  gap: 16px;
  overflow: hidden;

  .left-panel {
    width: 320px;
    background: #fff;
    border-radius: 6px;
    box-shadow: 0 1px 8px rgba(0,0,0,0.08);
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .panel-header {
      padding: 14px 16px;
      border-bottom: 1px solid #ebeef5;
      h3 { margin: 0; font-size: 16px; }
    }

    .course-list-container {
      flex: 1;
      overflow-y: auto;
      padding: 8px;
      .course-list {
        .course-item {
          padding: 12px;
          margin-bottom: 8px;
          border: 1px solid #ebeef5;
          border-radius: 6px;
          cursor: pointer;
          display: flex;
          justify-content: space-between;
          align-items: center;
          &:hover { background-color: #f9fafc; }
          &.active {
            border-color: #409eff;
            background-color: #ecf5ff;
          }
          .course-info .course-name {
            font-size: 15px;
            font-weight: 500;
            color: #303133;
          }
          .course-actions .el-button {
            width: 28px;
            height: 28px;
            padding: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            .el-icon { font-size: 14px; }
          }
        }
      }
    }

    .pagination-container {
      padding: 12px 16px;
      border-top: 1px solid #ebeef5;
    }
  }

  .right-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 16px;

    .course-detail-panel,
    .content-panel {
      background: #fff;
      border-radius: 6px;
      box-shadow: 0 1px 8px rgba(0,0,0,0.08);
      display: flex;
      flex-direction: column;
      overflow: hidden;

      .panel-header {
        padding: 14px 16px;
        border-bottom: 1px solid #ebeef5;
        h3 { margin: 0; font-size: 16px; }
      }

      .empty-state {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        .empty-content { padding: 30px; }
      }
    }

    .course-detail-panel {
      flex: 0 0 auto;
      max-height: 280px;
      .course-detail-content {
        padding: 16px;
        .detail-layout {
          display: flex;
          gap: 16px;
          height: 100%;
          .cover-section {
            flex: 0 0 140px;
            .course-cover {
              width: 100%;
              aspect-ratio: 16 / 9;
              object-fit: cover;
              border-radius: 4px;
            }
          }
          .description-section {
            flex: 1;
            overflow-y: auto;
            padding-right: 8px;
            .description-content {
              font-size: 14px;
              line-height: 1.5;
              color: #606266;
              white-space: pre-wrap;
            }
          }
        }
      }
    }

    .content-panel {
      flex: 1;
      min-height: 0;
      .content-wrapper {
        flex: 1;
        overflow: hidden;
      }
    }
  }
}

@media (max-width: 1200px) {
  .three-panel-management {
    flex-direction: column;
    .left-panel { width: 100%; max-height: 360px; }
    .right-panel .course-detail-panel { max-height: 240px; }
  }
}

@media (max-width: 768px) {
  .admin-courses-container { padding: 12px; }
  .left-panel { width: 100%; }
  .detail-layout {
    flex-direction: column;
    .cover-section { flex: 0 0 auto; }
    .course-cover { width: 100%; height: 160px; }
  }
}
</style>